<template>
  <div class="watermark_content">
    <el-button @click="fullScreenWatermark">点击添加全屏水印</el-button>
    <!-- <el-button @click="removeWatermark('fullScreenWatermark')">点击移除全屏水印</el-button> -->
  </div>
</template>
<script>
export default {
  name: 'Watermark',
  data() {
    return {}
  },
  mounted() {},
  methods: {
    fullScreenWatermark() {
      this.addWatermark(
        '水印文字',
        'fullScreenWatermark'
      )
    },
    removeWatermark(id) {
      if (document.getElementById(id) !== null) {
        document.getElementById('app').removeChild(document.getElementById(id))
      }
    },
    addWatermark(watermarkName, watermarkId, dom) {
      const canvas = document.createElement('canvas')
      if (dom) {
        canvas.width = this.$el.querySelector(dom)?.clientWidth || 0
        canvas.height = this.$el.querySelector(dom)?.clientHeight || 0
      } else {
        canvas.width = window.innerWidth
        canvas.height = window.innerHeight
      }
      const ctx = canvas.getContext('2d')
      const rotate = -5
      ctx.rotate((rotate * Math.PI) / 180)
      ctx.font = '14px Microsoft Yahei'
      ctx.fillStyle = 'rgb(184, 184, 184)'
      ctx.textBaseline = 'middle'
      ctx.translate(rotate * 10, 0)
      const textWidth = ctx.measureText(watermarkName).width
      const textHeight = 14 * 1.3
      const xNum = Math.ceil(canvas.width / textWidth)
      const yNum = Math.ceil(canvas.height / textHeight)
      const gap = 20
      for (let i = 0; i < xNum; i++) {
        for (let j = 0; j < yNum; j++) {
          ctx.fillText(
            watermarkName,
            i * (textWidth + gap),
            j * (textHeight + gap)
          )
        }
      }
      const div = dom ? this.$el.querySelector(dom) : this.$el
      div.id = watermarkId
      // div.style.pointerEvents = 'none'
      div.style.zIndex = 9999
      div.style.background =
        'url(' + canvas.toDataURL('image/png') + ') left top repeat'
      return watermarkId
    },
  },
}
</script>
<style lang="less" scoped>
.watermark_content {
  width: 100vw;
  height: 100vh;
}
</style>
